﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using WD.Db.Contract;
using WD.Framework.Contract;
using WD.Web.MVC.Common;

namespace WD.Web.MVC.Controllers.Filters
{
    public class WebOnlineFilter : AuthorizeAttribute, IExceptionFilter
    {
        /// <summary>
        /// 权限URL （默认为当前请求链接）
        /// </summary>
        public string Url { get; set; }
        /// <summary>
        /// 是否检测当前用户是商家
        /// </summary>
        public bool CheckShoper { get; set; }
        /// <summary>
        /// 登录超时返回JSON（用于弹框登录，默认false）
        /// </summary>
        public bool AjaxLogin { get; set; }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {

            if (StaticData.CurrentUser == null)
            {
                if (filterContext.HttpContext.Request.HttpMethod == "POST" || AjaxLogin)
                {
                    filterContext.Result = new JsonResult
                    {
                        Data = new
                        {
                            statusCode = CommonCode.Json结果代码_statusCode_登录超时,
                            message = "登录超时，请重新登录！"
                        },

                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    filterContext.Result = new RedirectResult("/Me/Login?fromurl=" + filterContext.HttpContext.Request.Url);
                }
            }
            //else
            //{
            //    if (CheckShoper)
            //    {
                    //if (StaticData.CurrentUser.Type == CommonCode.用户类型_商家)
                    //{
                    //    filterContext.Result = new JsonResult
                    //    {
                    //        Data = new
                    //        {
                    //            statusCode = CommonCode.Json结果代码_statusCode_错误,
                    //            message = "此页面需要商家权限！"
                    //        },
                    //        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    //    };
                    //}
            //    }

            //}
        }


        void IExceptionFilter.OnException(ExceptionContext filterContext)
        {
            filterContext.Result = new JsonResult
            {
                Data = new
                {
                    statusCode = CommonCode.Json结果代码_statusCode_错误,
                    message = filterContext.Exception.Message
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            filterContext.ExceptionHandled = true;
            //  throw new NotImplementedException();
        }
    }
}